package com.elem.web;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.elem.bean.Cart;
import com.elem.bean.Orders;
import com.elem.service.CartService;
import com.elem.service.OrdersService;
import com.elem.service.impl.CartServiceImpl;
import com.elem.service.impl.OrdersServiceImpl;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

// 目前只有两个：一个是登录，一个是注册
@WebServlet("/OrdersController/*")
public class OrdersServlet extends BaseServlet {
   OrdersService ordersService = new OrdersServiceImpl();

    ObjectMapper objectMapper = new ObjectMapper();
    public void createOrders(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取请求数据
        Orders orders = new Orders();
        try {
            BeanUtils.populate(orders, req.getParameterMap());
            int ordersId = ordersService.createOrders(orders);
            objectMapper.writeValue(resp.getOutputStream(), ordersId);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public void getOrdersById(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取请求数据
        String ordersId = req.getParameter("orderId");
        try {
            Orders orders = ordersService.getOrdersById(Integer.parseInt(ordersId));
            objectMapper.writeValue(resp.getOutputStream(), orders);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public void listOrdersByUserId(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取请求数据
        String userId = req.getParameter("userId");
        try {
            List<Orders> ordersList = ordersService.listOrdersByUserId(userId);
            objectMapper.writeValue(resp.getOutputStream(), ordersList);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}